//
//     Copyright (c) 2015 Qiwei.Gu(gqwmail@qq.com) All rights reserved.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the sub language governing permissions and
//   limitations under the License.
//
#include "config_mgr.h"

#include "config.h"
#include "log/log.h"

bool ConfigMgr::init()
{
    return true;
}

bool ConfigMgr::addConfig(ConfigType type, std::shared_ptr<IConfig> config)
{
    if (!config)
    {
        LOG_ERROR("Add config failed, config is null. config type: " << (int)type) ;
        return false;
    }
    if (!config->init())
    {
        LOG_ERROR("Config init failed, config type: " << (int)type) ;
        return false;
    }
    configs_[type] = config;
    LOG_INFO("Add config suc, config type is " <<  (int)type) ;
    return true;
}

bool ConfigMgr::addConfigNoInit(ConfigType type, std::shared_ptr<IConfig> config)
{
    if (!config)
    {
        LOG_ERROR("Add config failed, config is null. config type: " << (int)type) ;
        return false;
    }
    configs_[type] = config;
    LOG_INFO("Add config suc, config type is " <<  (int)type) ;
    return true;
}

std::shared_ptr<IConfig> ConfigMgr::getConfig(ConfigType type)
{
    auto it = configs_.find(type);
    return it == configs_.end() ? std::shared_ptr<IConfig>() : it->second;
}

/**
 * @desc 重新加载指定配置
 * @param type 配置类型
 * @auth Qiwei.Gu
 * @date 2015-04-06 16:49:06
 */
bool ConfigMgr::reload(ConfigType type)
{
    auto config = getConfig(type);
    if (!config)
    {
        LOG_WARN("Not found config, type:" << (int)type);
        return false;
    }
    auto newConfig = config->makeNewObject();
    if (!newConfig)
    {
        LOG_WARN("Create new config failed, type:" << (int)type);
        return false;
    }
    return addConfig(type, newConfig);
}
